
<template>

  <el-dialog
    ref="refDlg"
    :title="title"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="clearForm"
    width="600px"
    top="8vh"
    @close="closeDialog"
  >
    <c-list :column="2">
      <c-list-item label="门店建设项目号" :value="rowData.constCode" />
      <c-list-item label="门店测绘批次" :value="rowData.surveyBatchCode" />
      <c-list-item label="当前测绘进度" dict-type-code="SHOP_SURVEY_STATE" :value="rowData.state" />
      <c-list-item label="门店名称" :value="rowData.shopName" />
    </c-list>
    <c-list :column="1">
      <c-list-item label="所属客户" :value="rowData.clientName" />
      <c-list-item label="所属办事处" :value="rowData.officeName" />
    </c-list>

    <el-form
      ref="refForm"
      :rules="rules"
      :model="formData"
      size="mini"
    >
      <el-row v-if="dlgType==='delay'">
        <el-col :span="24">
          <el-form-item label="调整后预计测绘申请提报时间:" prop="afterAdjustTime">
            <el-date-picker
              v-model="formData.afterAdjustTime"
              type="date"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd 23:59:59"
              placeholder="选择日期"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="dlgType==='delay'">
        <el-col :span="24">
          <el-form-item label="延期原因:" prop="exceptionDesc">
            <el-input v-model="formData.exceptionDesc" maxlength="1000" show-word-limit type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="dlgType==='remap'">
        <el-col :span="24">
          <el-form-item label="复尺说明:" prop="resurveyApplyDesc">
            <el-input v-model="formData.resurveyApplyDesc" maxlength="1000" show-word-limit type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="dlgType==='terminal'">
        <el-col :span="24">
          <el-form-item label="终止原因:" prop="endReason">
            <el-input v-model="formData.endReason" maxlength="1000" show-word-limit type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="dlgType==='unRemap'">
        <el-col :span="12">
          <el-form-item label="不复尺类型:" prop="exceptionType">
            <el-select
              v-model="formData.exceptionType"
              placeholder="请选择"
              style="width: 100%"
              @focus="getDictByPatchTypeAll"
            >
              <el-option
                v-for="item in unRemapOptions"
                :key="item.dictCode"
                :label="item.dictName"
                :value="item.dictCode"
                :disabled="item.dictCode==='A'&&rowData.unresurveyDesignSetup === 'C'?true:false"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="dlgType==='unRemap'">
        <el-col :span="24">
          <el-form-item label="不复尺说明:" prop="exceptionDesc">
            <el-input v-model="formData.exceptionDesc" maxlength="1000" show-word-limit type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="申请人:" prop="applicantCode">
            {{ this.$store.getters.user.data.userName||'-' }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申请时间:" prop="applyTime">
            {{ nowTime() }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="dlgType==='unRemap'&&configAttachmentId">
        <el-col v-loading="fileLoading" :span="24">
          <el-form-item label="不复尺异常附件" prop="fileList">
            <file-uploader
              :data="fileList"
              :limit="20"
              :config-attachment-id="configAttachmentId"
              :file-type="fileTypeName"
              @remove="removeFile"
              @upload-success="uploadSuccessFile"
            />
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="closeDialog">取 消</el-button>
      <el-button :loading="saveLoading" size="mini" type="primary" @click="submitAudit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { nowTime } from '@/utils/tool.js'
import { getExceptionType, getShopAttachment } from '@/api/common'
import FileUploader from '@/components/importFile'
import { getDictByPatchType } from '@/api/dataDict'
import { saveException, saveTerminal, saveState, postConfigAttachmentTemplate, isConfirm } from '@/api/shopMap'
export default {
  name: 'FormDialog',
  components: { FileUploader },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    rowData: {
      type: Object,
      default: () => ({})
    },
    dlgType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          var date = new Date()
          var y = date.getFullYear()
          var m = date.getMonth() + 1
          var d = date.getDate()
          var nowTime = new Date(`${y}-${m}-${d} 00:00:00`)
          return time.getTime() < nowTime.getTime()
        }
      },
      fileType: '',
      nowTime,
      saveLoading: false,
      fileList: [], // 附件上传
      allFileList: [],
      fileLength: 0, // 附件长度
      fileLoading: false,
      configAttachmentId: '',
      fileTypeName: '',
      unRemapOptions: [], // 不复尺类型
      formData: {
        id: '',
        constCode: '',
        state: ''// 进度
      },
      rules: {
        afterAdjustTime: [
          { required: true, message: '请选择调整后预计测绘申请提报时间', trigger: 'change' }
        ],
        exceptionDesc: [
          { required: true, message: '请填写', trigger: 'change' }
        ],
        resurveyApplyDesc: [
          { required: true, message: '请填写复尺说明', trigger: 'change' }
        ],
        endReason: [
          { required: true, message: '请填写终止原因', trigger: 'change' }
        ],
        exceptionType: [
          { required: true, message: '请选择不复尺类型', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    title() {
      let thisTitle
      switch (this.dlgType) {
        case 'delay':
          thisTitle = '延期申请'
          break
        case 'terminal':
          thisTitle = '终止任务'
          break
        case 'remap':
          thisTitle = '复尺申请'
          break
        case 'unRemap':
          thisTitle = '不复尺申请'
          break
      }
      return thisTitle
    }
  },
  async created() {
    if (this.rowData && this.rowData.id) {
      // this.formData.constCode = this.rowData.constCode
      this.formData.state = this.rowData.state
      this.formData.id = this.rowData.id
      this.getFileType()// 获取附件
    }
  },
  methods: {
    async getFileType() {
      this.fileLoading = true
      await postConfigAttachmentTemplate().then(res => {
        if (res.success === 1) {
        // 根据modelId获取每个配置id
          const arrTemp = res.data.records.filter(row => row.attachmentType === '不复尺异常附件')
          if (arrTemp.length > 0) {
            this.configAttachmentId = arrTemp[0].id
            this.fileTypeName = arrTemp[0].fileTypeName
          }
        }
      })
      this.getFiles()// 获取文件，图片列表
    },
    getFiles() {
      getShopAttachment(this.rowData.id).then(res => {
        if (res.success === 1) {
        // 根据modelId获取每个配置id
          this.allFileList = res.data
          res.data.map(row => {
            if (row.attachmentType === '不复尺异常附件') {
              this.fileList.push(row)
            }
          })
          this.fileLength = this.fileList.length
          this.fileLoading = false
        }
      }).catch(() => {
        this.fileLoading = false
      })
    },
    // 删除文件
    removeFile({ list, fileLength }) {
      this.fileLength = fileLength
    },
    // 文件上传成功
    uploadSuccessFile({ list, fileLength }) {
      this.fileLength = fileLength
    },
    async getDictByPatchTypeAll() {
      const { UNRESURVEY_TYPE } = await getDictByPatchType(['UNRESURVEY_TYPE'])
      this.unRemapOptions = UNRESURVEY_TYPE
      // if (this.rowData.unresurveyDesignSetup === 'C') {
      //   unresurveyDesignSetup
      // }
    },
    clearForm() {
      this.closeDialog()
      this.formData = {}
    },
    submitAudit() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          if (this.dlgType === 'delay') {
            this.saveDelay()
          } else if (this.dlgType === 'terminal') {
            this.saveTerminal()
          } else if (this.dlgType === 'remap') {
            this.saveRemap()
          } else {
            this.saveUnRemap()
          }
        }
      })
    },
    closeDialog() {
      this.saveLoading = false
      this.$emit('update:visible', false)
    },
    async   saveDelay() {
      await getExceptionType('测绘延期申请').then(res => {
        if (res.success === 1 && res.data.records.length > 0) {
          this.$set(this.formData, 'exceptionHandleId', res.data.records[0].id)
        }
      })

      const submitForm = {
        modelId: this.formData.id,
        exceptionHandleId: this.formData.exceptionHandleId || '',
        constCode: this.rowData.constCode || '',
        bizCode: this.rowData.surveyBatchCode || '',
        bizName: '测绘延期申请',
        exceptionDesc: this.formData.exceptionDesc,
        belongModel: 'SHOP_SURVEY',
        state: 'A',
        shopExceptionDetailDTOS: [
          {
            afterAdjustTime: this.formData.afterAdjustTime || '',
            beforeAdjustTime: this.rowData.expectApplySurveyTime || '',
            exceptionDesc: this.formData.exceptionDesc,
            applicantCode: this.$store.getters.user.data.account || '',
            applyTime: nowTime()
          }
        ]
      }
      if (!submitForm.exceptionHandleId) {
        this.$message.warning('未获取到异常配置id')
        return
      }
      this.saveLoading = true
      saveException(submitForm).then(res => {
        if (res.success === 1) {
          this.$message.success('延期申请提交成功')
          this.$emit('success', true)
          this.clearForm()
          this.saveLoading = false
        }
      }).catch(() => {
        this.saveLoading = false
      })
    },
    countDays(date2, date1) {
      const date = (new Date(date2).getTime() - new Date(date1).getTime()) / (1000 * 60 * 60 * 24)
      return Math.ceil(date)
    },
    saveTerminal() {
      this.saveLoading = true
      const submitForm = {
        applicantCode: this.$store.getters.user.data.account,
        applyTime: nowTime(),
        dataSource: 'ARTIFICIAL',
        state: this.formData.state,
        constCode: this.rowData.constCode,
        endReason: this.formData.endReason,
        id: this.formData.id
      }
      isConfirm({ constCode: this.rowData.constCode }).then(res => {
        if (res.msg === '1') {
          this.$confirm('当前操作将终止当前测绘任务，同时终止对应的门店建设项目号，是否确认?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            saveTerminal(submitForm).then(res => {
              if (res.success === 1) {
                this.$message.success('终止任务成功')
                this.$emit('success', true)
                this.clearForm()
                this.saveLoading = false
              }
            })
          }).catch(() => {
            this.clearForm()
            this.saveLoading = false
          })
        } else {
          saveTerminal(submitForm).then(res => {
            if (res.success === 1) {
              this.$message.success('终止任务成功')
              this.$emit('success', true)
              this.clearForm()
              this.saveLoading = false
            }
          })
        }
      })
    },
    saveRemap() {
      this.saveLoading = true
      this.$set(this.formData, 'constCode', this.rowData.constCode)
      this.$set(this.formData, 'unresurveyDesignConst', this.rowData.unresurveyDesignConst)
      this.$set(this.formData, 'unresurveyDesignSetup', this.rowData.unresurveyDesignSetup)
      this.$set(this.formData, 'resurveyApplicantName', this.$store.getters.user.data.userName)// 复尺申请人
      this.$set(this.formData, 'resurveyApplyTime', nowTime())// 复尺申请时间
      this.$set(this.formData, 'shopAttachmentDTOList', this.allFileList)
      saveState(this.formData).then(res => {
        if (res.success === 1) {
          this.$message.success('复尺申请成功')
          this.$emit('success', true)
          this.clearForm()
          this.saveLoading = false
        }
      })
    },
    async   saveUnRemap() {
      if (this.formData.exceptionType === 'A') {
        await getExceptionType('不复尺设计摆场图').then(res => {
          if (res.success === 1 && res.data.records.length > 0) {
            this.$set(this.formData, 'exceptionHandleId', res.data.records[0].id)
          }
        })
      } else {
        await getExceptionType('不复尺设计施工图').then(res => {
          if (res.success === 1 && res.data.records.length > 0) {
            this.$set(this.formData, 'exceptionHandleId', res.data.records[0].id)
          }
        })
      }

      const submitForm = {
        modelId: this.formData.id,
        constCode: this.rowData.constCode,
        exceptionHandleId: this.formData.exceptionHandleId,
        bizCode: this.rowData.surveyBatchCode,
        bizName: this.formData.exceptionType === 'A' ? '不复尺设计摆场图' : '不复尺设计施工图',
        belongModel: 'SHOP_SURVEY',
        // state: this.rowData.state,
        exceptionDesc: this.formData.exceptionDesc,
        shopAttachmentDTOS: this.fileList,
        shopExceptionDetailDTOS: [
          {
            // exceptionType: this.formData.exceptionType,
            exceptionDesc: this.formData.exceptionDesc,
            applicantCode: this.$store.getters.user.data.account,
            applyTime: nowTime()
          }
        ]
      }
      if (!submitForm.exceptionHandleId) {
        this.$message.warning('未获取到异常配置id')
        return
      }
      if (this.fileLength === 0) {
        this.$message.warning('请上传不复尺附件')
        return
      }
      if (submitForm.bizName === '不复尺设计施工图') {
        this.$confirm('审核通过后，将不需复尺直接完结当前测绘任务，是否确认？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.saveLoading = true
          saveException(submitForm).then(res => {
            if (res.success === 1) {
              this.$message.success('不复尺设计施工图申请成功')
              this.$emit('success', true)
              this.clearForm()
              this.saveLoading = false
            }
          })
        })
      } else {
        this.saveLoading = true
        saveException(submitForm).then(res => {
          if (res.success === 1) {
            this.$message.success('不复尺设计摆场图申请成功')
            this.$emit('success', true)
            this.clearForm()
            this.saveLoading = false
          }
        })
      }
    }
  }
}
</script>
<style lang='scss' scoped>
/* @import url(); 引入css类 */

</style>
